package com.wgz.medicalmanagement.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.wgz.medicalmanagement.domain.entity.User;
import com.wgz.medicalmanagement.repository.UserRepository;
import com.wgz.medicalmanagement.repository.UserDao;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 实现Spring Security的UserDetailsService接口，用于加载用户详情
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;
    private final UserDao userDao;

    /**
     * 根据用户名加载用户详情
     *
     * @param username 用户名
     * @return UserDetails对象
     * @throws UsernameNotFoundException 如果用户名不存在
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("正在加载用户：{}", username);
        
        // 从数据库中查询用户
        User user = userDao.findByUsername(username);
        if (user == null) {
            log.error("用户名不存在：{}", username);
            throw new UsernameNotFoundException("找不到用户：" + username);
        }
        
        // 如果用户被禁用，返回错误
        if (!Boolean.TRUE.equals(user.getEnabled())) {
            log.error("用户账户已禁用：{}", username);
            throw new UsernameNotFoundException("用户账户已禁用：" + username);
        }
        
        // 创建并返回UserDetails对象
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getEnabled(), // enabled
                user.getAccountNonExpired(), // accountNonExpired
                user.getCredentialsNonExpired(), // credentialsNonExpired
                user.getAccountNonLocked(), // accountNonLocked
                getAuthorities(user)
        );
    }

    /**
     * 根据用户角色获取其权限
     *
     * @param user 用户
     * @return 权限集合
     */
    private Collection<? extends GrantedAuthority> getAuthorities(User user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        // 添加基本角色
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        
        // 如果有角色信息，添加角色权限
        if (user.getRole() != null) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole().name()));
            
            // 根据角色添加具体权限
            switch (user.getRole()) {
                case ADMIN:
                    authorities.add(new SimpleGrantedAuthority("ADMIN_ACCESS"));
                    break;
                case DOCTOR:
                    authorities.add(new SimpleGrantedAuthority("DOCTOR_ACCESS"));
                    break;
                case NURSE:
                    authorities.add(new SimpleGrantedAuthority("NURSE_ACCESS"));
                    break;
                case PATIENT:
                    authorities.add(new SimpleGrantedAuthority("PATIENT_ACCESS"));
                    break;
                default:
                    break;
            }
        }
        
        return authorities;
    }
} 